<?php
//这里是安装程序
$GLOBALS["extension"]=@get_loaded_extensions();
if($GLOBALS["extension"]==false) {
    $GLOBALS["extension"]=array();
}
class installCon
{
    public $alevel=["admin"];
    public $extension=[];
    function __construct(){
        //判断是否已安装了
        if(!Config(".install")){
            die('UCMS已安装 <a href="http://uuu.la/help/reinstall.html" target="_blank">如何重新安装</a>  <a href="../'.AdminDir.'">点此进入后台</a>'.is_cachephpcode());
        }

    }
    function __init(){

    }
    function index(){
        $this->extension=@get_loaded_extensions();
        if($this->extension==false) {
            $this->extension=array();
        }
        $data=["info"=>"","disableinstall"=>0,"cachedirtips"=>""];
        if(!ext_exist('mysql',1) && !ext_exist('pdo_mysql',1) && !ext_exist('pdo_sqlite',1)) {
            if(count($this->extension)==0) {
                $data["info"].='get_loaded_extensions函数被禁用,无法判断是否能安装<br>';
            }
            $data["info"].='当前空间不支持系统所需的数据库连接方式,无法进行安装<br>';
            $data["disableinstall"]=1;
        }
        if($this->dir_test('cache')) {
            $data["cachedirtips"]='支持';
        }else {
            $data["info"].='缓存目录cache不可写,无法进行安装<br>';
            $data["disableinstall"]=1;
            $data["cachedirtips"]='支持';
        }
        if($this->dir_test('public/uploadfile')) {
            $data["uploadfiledirtips"]='支持';
        }else {
            $data["info"].='上传目录uploadfile不可写,无法上传文件<br>';
            $data["uploadfiledirtips"]='不可写';
        }
        if($this->dir_test('App/config')) {
            $data["incdirtips"]='支持';
        }else {
            $data["info"].='config目录不可写,无法使用<br>';
            $data["incdirtips"]='不可写';
        }
        $data["step"]=0;
        show(".step",$data);
    }
    function step1(){
        $data=[
            "mysqldatabase"=>true,
            "sqlitedatabase"=>true,

        ];
        if(ext_exist('pdo_mysql',1)==true){
            $data["defaultmysql"]='mysqlpdo';
        }elseif(ext_exist('mysql',1)==true) {
            $data["defaultmysql"]='mysql';
        }else {
            $data["defaultmysql"]='';
            $data["mysqldatabase"]=false;
        }
        if(ext_exist('pdo_sqlite',1)==false) {
            $data["sqlitedatabase"]=false;
        }
        //随机生成sql数据库的名字
        $data["sqlite_dbname"]=substr(md5(rand(9999999,99999999).time().rand(9999999,999999999).'pa*3'),0,16).'.db';
        if ($this->is_rew()){
            $data["ifrewrite"]=true;
            $data["installdir"]="/";
            $data["rewritetesturi"]='//'.$_SERVER['HTTP_HOST'].'/rewrite_test'.rand(666,1024).'.html';
        }else{
            $data["ifrewrite"]=false;
        }
        $data["step"]=1;
        show(".step",$data);
    }
    function step2(){
        $installinfo=array();
        foreach($_POST as $key=>$val) {
            $_POST[$key]=trim($val);
        }
        if($_POST['database']=='mysqlpdo' || $_POST['database']=='mysql') {
            $installinfo['sitedb']="array('database'=>'".$_POST['database']."','host'=>'".$_POST['mysql_host']."','dbname'=>'".$_POST['mysql_dbname']."','user'=>'".filespecialchars($_POST['mysql_user'])."','password'=>'".filespecialchars($_POST['mysql_password'])."')";
        }elseif($_POST['database']=='sqlitepdo') {
            if(substr($_POST['sqlite_dbfile'],strlen($_POST['sqlite_dbfile'])-3,3)!=='.db') {
                $_POST['sqlite_dbfile'].='.db';
            }
            $installinfo['sitedb']="array('database'=>'sqlitepdo','dbfile'=>IncDir.'".$_POST['sqlite_dbfile']."')";
        }
        else {die('error');}
        $_POST['tableex']=strtolower($_POST['tableex']);
        if(!preg_match("/^[a-z0-9_]+$/",$_POST['tableex'])){
            die('表名前缀格式不正确');
        }
        $installinfo['tableex']='\''.$_POST['tableex'].'\'';
        $installinfo['version']='\''.version.'\'';
        $installinfo['MysqlEngine']='\''.MysqlEngine.'\'';
        $installinfo['systemdomain']='\''.trim($_POST['systemdomain']).'\'';
        if($_POST['urlrewrite']==1) {
            $installinfo['urlrewrite']='1';
        }else {
            $installinfo['urlrewrite']='0';
        }
        $installinfo['sitehash']='\''.substr(md5(rand(1000000,9999999).time()),0,20).'\'';
        //获取安装目录
        $document_root=str_replace('/','\\',$_SERVER["DOCUMENT_ROOT"]);
        if(substr($document_root,strlen($document_root)-1,1)!='\\') {
            $document_root.=DIRECTORY_SEPARATOR;
        }
        $script_root=dirname(dirname(__FILE__));
        if(substr($script_root,strlen($script_root)-1,1)!='\\') {
            $script_root.=DIRECTORY_SEPARATOR;
        }
        $installinfo['systemdir']=get_installdir();
        $installinfo['systemdir']='\''.str_replace('\\','/',$installinfo['systemdir']).'\'';

        $configcontent=file_get_contents('../inc/config_default.php');
        if(!$configcontent) {
            echo('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">');
            die('/inc/config_default.php文件不存在');
        }
        foreach($installinfo as $key=>$val) {
            $configcontent=str_replace('\'{'.$key.'}\'',$val,$configcontent);
        }
        //创建数据库
        if($_POST['database']=='mysqlpdo' || $_POST['database']=='mysql') {//mysql数据库
            $site_db=array('database'=>$_POST['database'],'host'=>$_POST['mysql_host'],'dbname'=>'','user'=>$_POST['mysql_user'],'password'=>$_POST['mysql_password']);
            $db = new db();
            $db -> connect($site_db);
            $db ->query('CREATE DATABASE IF NOT EXISTS `'.$_POST['mysql_dbname'].'` ');
            $alldb = $db -> all('SHOW DATABASES');
            $ifin=0;
            foreach($alldb as $val) {
                if($val['Database']==$_POST['mysql_dbname']) {
                    $ifin=1;
                    break;
                }
            }
            if($ifin==0) {
                echo('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">');
                die('创建数据库失败,请确认您的mysql账号'.$_POST['mysql_dbname'].'是否有创建数据库权限,或者手动建立数据库');
            }
            $site_db=array('database'=>$_POST['database'],'host'=>$_POST['mysql_host'],'dbname'=>$_POST['mysql_dbname'],'user'=>$_POST['mysql_user'],'password'=>$_POST['mysql_password']);
            $sqlcontent=file_get_contents('mysql.sql');
        }elseif($_POST['database']=='sqlitepdo') {
            $site_db=array('database'=>'sqlitepdo','dbfile'=>IncDir.$_POST['sqlite_dbfile']);
            $fp = @fopen(IncDir.$_POST['sqlite_dbfile'],"wb");
            if(!@fwrite($fp,' ')){
                echo('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">');
                die('创建SQLite数据库失败,请确认INC目录下拥有写权限');
                fclose($fp);
            }
            fclose($fp);
            unlink(IncDir.$_POST['sqlite_dbfile']);
            $sqlcontent=file_get_contents('sqlite.sql');
        }
        if(strlen($sqlcontent)<10) {
            echo('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">');
            die('读取sql文件失败,请确认install/mysql.sql或install/sqlite.sql是否存在');
        }
        $db = new db();
        $db -> connect($site_db);
        $sqlcontent=str_replace('uuu_',$_POST['tableex'],$sqlcontent);
        $sqlcontent=str_replace('MyISAM',MysqlEngine,$sqlcontent);
        $allsql=explode(';',$sqlcontent);
        foreach($allsql as $thisql) {
            $thisql.=';';
            if(strlen($thisql)>5) {
                $return=$db ->query($thisql);
            }
        }
        //写入配置文件
        $fp = fopen($configfile,"w");
        if(!fwrite($fp,$configcontent)){
            fclose($fp);
            echo('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">');
            die('配置文件写入失败,请赋予inc/config.php写权限');
        }
        fclose($fp);
        if(isset($_COOKIE["ucmsid"]) && !empty($_COOKIE["ucmsid"])) {
            $ucmsid=dbstr($_COOKIE["ucmsid"]);
            unset($_COOKIE["ucmsid"]);
        }else {
            $ucmsid='';
        }
        if(!preg_match("/^[a-zA-Z0-9_]+$/",$_POST['uuuadminname'])){
            die('用户名格式不正确');
        }
        $goodadmin=array(
            "username"=>$_POST['uuuadminname'],
            "psd"=>password_md5($_POST['uuuadminpassword']),
            "nickname"=>'管理员',
            "alevel"=>3,
            "kind"=>'0',
            "ucmsid"=>$ucmsid,
            "power"=>'{"b":{"1":1,"2":1},"alevel":3}'
        );
        $id = $db -> insert($_POST['tableex'].'admin',$goodadmin);
        if($id>0) {
            ?>
            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
            <html xmlns="http://www.w3.org/1999/xhtml">
            <head>
                <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
                <title>安装成功</title>
                <style>
                    a{color:blue}
                    body{text-align:center;font-size:16px;padding-top:50px;}
                </style>
            </head>
            <body>
            UCMS安装成功,请牢记您的账号密码,默认后台路径为<?php echo(AdminDir);?>,<a href="../<?php echo(AdminDir);?>/login.php" target="_blank">点此进入后台</a>
            <br><br>帮助:
            <a href="http://uuu.la/help/admindir.html" target="_blank">如何修改后台路径</a>
            <a href="http://uuu.la/help/adminhelp.html" target="_blank">后台使用说明</a>
            <a href="http://uuu.la/help/adminkey.html" target="_blank">后台快捷键使用技巧</a>
            <a href="http://uuu.la/help/faster.html" target="_blank">UCMS性能优化</a>
            <a href="http://uuu.la/services/" target="_blank">UCMS授权购买</a>
            </body>
            </html>
            <?php
            die('');
        }else {
            echo('<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">');
            die('添加管理员失败,请确认数据库权限,删除数据库后重试');
        }
    }

    function dir_test($dir) {
        $dir=ROOT.'/'.$dir.'/rwtest/';
        if(is_dir($dir)) {

        }else {
            createDir($dir);
            if(!is_dir($dir)) {
                Return false;
            }
        }
        $filename=$dir.'test.txt';
        $fp = @fopen($filename,"w");
        if(!@fwrite($fp,"readwritetest")){
            @fclose($fp);
            rmdir($dir);
            Return false;
        }else {
            @fclose($fp);
            unlink($filename);
        }
        rmdir($dir);
        Return true;
    }
    private function get_installdir() {
        $_SERVER['PHP_SELF']=str_replace('\\','/',$_SERVER['PHP_SELF']);
        $dir=str_replace('install/index.php','',$_SERVER['PHP_SELF']);
        Return $dir;
    }
    //判断是否支持伪静态
    private  function is_rew(){
        $testurl='http://'.$_SERVER['HTTP_HOST'].'/rewrite_test'.rand(666,1024).'.html';
        $c1=mcurl::new();
        $data=$c1->get($testurl);
        $d=json_decode($data,1);
        return count($d)>0?true:false;
    }
    function filespecialchars($str) {
        Return str_replace("'","\\'",$str);
    }
}
function ext_exist($extname,$returnkind=0) {
    global $extension;
    if(in_array($extname,$extension)) {
        if($returnkind) {
            Return true;
        }
        echo('支持');
    }else {
        if($returnkind) {
            Return false;
        }
        if($extname=='pdo_sqlite') {echo('无法使用sqlite数据库');Return ;}
        if($extname=='pdo_mysql') {echo('不支持,建议使用pdo方式连接mysql');Return ;}
        if($extname=='mysql') {echo('建议使用pdo方式连接mysql');Return ;}
        if($extname=='json') {echo('必须使用该组件');Return ;}
        echo('不支持');
    }
}